//
//  IMessageContentParser.m
//  imessagesender
//
//  Created by Pang lei on 13-7-26.
//  Copyright (c) 2013年 Pang lei. All rights reserved.
//

#import "IMessageContentParser.h"
#import "IMessageImageNode.h"
#import "IMessageContentNode.h"
#import "IMessageContent.h"
#import "GDataXMLNode.h"

@implementation IMessageContentParser

+ (IMessageContent *)parse:(NSString *)path
{
    IMessageContent *content = [[IMessageContent alloc] init];
    GDataXMLDocument *doc = [IMessageContentParser loadGDataXMLDocument:path];
    GDataXMLElement *root = doc.rootElement;
    // add taskId
    content.taskId = [IMessageContentParser parseTaskId:root];
    
    NSArray *child  = root.children;
    for(GDataXMLElement *element in child) {
        NSString *tagName = [element name];
        if ([tagName isEqualToString:@"paragraph"]) {
            IMessageContentNode *contentNode = [IMessageContentParser buildContentNode:element];
            [content addObject:contentNode];
        } else if ([tagName isEqualToString:@"image"]) {
            IMessageImageNode *imageNode = [IMessageContentParser buildImageNode:element];
            [content addObject:imageNode];
        } else {
            continue;
        }
    }
    return content;
}

+ (NSString *) parseTaskId:(GDataXMLElement *)rootElement
{
    GDataXMLNode *node = [rootElement attributeForName:@"taskId"];
    NSString *taskId = [node stringValue];
    return taskId;
}

+ (IMessageImageNode *)buildImageNode:(GDataXMLElement *)element
{
    GDataXMLNode *node = [element attributeForName:@"uri"];
    NSString *uri = [[[node stringValue] componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
    IMessageImageNode *imageNode = [[IMessageImageNode alloc] initWithUri:uri];
    return imageNode;
}

+ (IMessageContentNode *)buildContentNode:(GDataXMLElement *)element
{
    NSString *content = [[[element stringValue] componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
    IMessageContentNode *contentNode = [[IMessageContentNode alloc] initWithContent:content];
    return contentNode;
}

+ (GDataXMLDocument *)loadGDataXMLDocument:(NSString *)xmlPath
{
    NSData *xmlData = [NSMutableData dataWithContentsOfFile:xmlPath];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:NULL];
    return doc;
}

@end
